package com.panopset.io;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;

import static com.panopset.Util.*;

import com.panopset.io.JarResources;

/**
 * Access to a flat jar file.
 *
 * Useful for a set of icons used in a video game sprite, for example.
 *
 * @author Karl Dinwiddie
 *
 */
public class JarResourceCollection {
    public String extension;
    public final File jarFile;
    public final JarResources jarResources;

    /**
     * Use this constructor if you would like a homogeneous set of resources,
     * for example all ".png" images.
     *
     * @param srcPath Java package path, for example "/com/panopset/nls/flagicons.jar"
     * @param workPath The jar must be extracted from the Java class resource to a work directory.
     * @param extension ".png" for example
     */
    public JarResourceCollection(String srcPath, String workPath, String extension) throws IOException {
        this.extension = extension;
        this.jarFile = savePackageResource(srcPath, workPath);
        this.jarResources = new JarResources(this.jarFile);
    }

    /**
     * Use this constructor if you would like access to all objects in the jar.
     * @param srcPath
     * @param workPath
     */
    public JarResourceCollection(String srcPath, String workPath) throws IOException {
        this(srcPath, workPath, EMPTY_STRING);
    }

    /**
     * Extract and list resources.
     *
     * @param targetPath Directory you would like the resources stored.
     * @return String list of resources, with the extension dropped.
     * @throws IOException
     */
    public String extractAndListResources(String targetPath) throws IOException {
            StringWriter sw = new StringWriter();
            for (String k : jarResources.getSizes().keySet()) {
                if (!isPopulated(k) || k.indexOf(extension) > 0) {
                    String name = dropPath(k);
                    sw.append(dropExtension(name));
                    sw.append(getReturnChar());
                    saveBytesToFile(jarResources.getResource(k),
                            new File(targetPath + "/" + name));
                }
            }
            return sw.toString();
    }

}
